package com.wht.utils;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 自定义一个工具类: 封装带有日期类型的javaBean
 */
public class MyBeanUtils {
    /**
     * 作用: 将没有日期类型的数据封装到javaBean对象
     * @param obj: javaBean对象
     * @param request: request.getParameterMap();
     */
    public static void  toBean(Object obj, HttpServletRequest request){
        try {
            BeanUtils.populate(obj,request.getParameterMap());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 作用: 将带有日期类型的数据封装到javaBean对象
     * @param obj: javaBean对象
     * @param request: request.getParameterMap();
     * @param datePatterns: 用户传递的日期数据的格式
     */
    public static void  toBeanWithDate(Object obj, HttpServletRequest request, String datePatterns){
        try {
            DateConverter dateConverter = new DateConverter();
            dateConverter.setPattern(datePatterns);//用户传递的日期格式
            ConvertUtils.register(dateConverter, Date.class);//string---Date
            BeanUtils.populate(obj,request.getParameterMap());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
